﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.SessionState;
using System.Data;
using System.IO;

using Newtonsoft.Json;
using Framework.DataAccess;
using Framework.Common.JsonEntities;
using Framework.Common;
using Framework.Common.Common;
using Mode;


namespace WebSite.WebServer
{
    /// <summary>
    /// ExamOnline 的摘要说明
    /// </summary>
    public class ExamOnline : IHttpHandler,IRequiresSessionState
    {
        JsonReturnMessages msg;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

              msg = new JsonReturnMessages();
              try
              {

                  if (context.Request.Params["Action"] == "SaveExam")
                      SaveExam();
                  if (context.Request.Params["Action"] == "GetExam")
                      GetExam();
                  if (context.Request.Params["Action"] == "SaveExamALL")
                      SaveExamALL();
                  if (context.Request.Params["Action"] == "InitExam")
                      InitExam();
                  if (context.Request.Params["Action"] == "examinationList")
                      GetexaminationList();
                  if (context.Request.Params["Action"] == "GetExamView")
                         GetExamView();
                  

                  
              }
              catch (Exception err)
              {
                  var message = err.Message;
                  if (err.InnerException != null && err.InnerException.Message != null)
                      message += "<BR>" + err.InnerException.Message;

                  msg.IsSuccess = 0;
                  msg.Msg = message;

                  var json = JsonConvert.SerializeObject(msg);
                  context.Response.Write(json);
              }
              context.Response.End();
        }
        /// <summary>
        /// 时时保存
        /// </summary>
        void SaveExam()
        {
            var context = System.Web.HttpContext.Current;
            int uid = context.Request.Params["uid"].ToInt();
            int topicid = context.Request.Params["topicid"].ToInt();
            int anserid = context.Request.Params["anserid"].ToInt();
            int topicType = context.Request.Params["topicType"].ToInt();
            int kaoshiId = context.Request.Params["kaoshiId"].ToInt();
            int dzfen = 0;
            if (topicType == 6)
            {
                int spanRate = context.Request.Params["spanRate"].ToInt(0);
                int score = context.Request.Params["score"].ToInt(0);
                if (spanRate != 0 && score != 0) {
                    dzfen = Convert.ToInt32(((spanRate / 100) * score));
                }

            }

            //多选选择题 是否选种该项
            int isWrite = context.Request.Params["isWrite"].ToInt();
            int code = context.Request.Params["code"].ToInt();
            string val = context.Request.Params["anval"];
          

              msg.IsSuccess = 0;
            if (uid > 0 && topicid > 0 && anserid > 0) { 
               //提交数据库
                ExamOlineDA db = new ExamOlineDA();
                if (db.replyAnswer(uid, kaoshiId, topicid, anserid, topicType, isWrite, code, val, dzfen) != 0)
                {
                    msg.IsSuccess = 0;
                    msg.Msg = "数据提交失败";
                }
                else
                {
                    msg.IsSuccess = 1;
                }
          
            }



            context.Response.Write(JsonConvert.SerializeObject(msg));
        
        }
        /// <summary>
        /// （结束）评分提交
        /// </summary>
        void SaveExamALL()
        {
            var context = System.Web.HttpContext.Current;
            int cdid = context.Request.Params["kaoshiId"].ToInt();
            int examid = context.Request.Params["examid"].ToInt();
            string topAll = context.Request.Params["topall"];
            
             DateTime dt1 = DateTime.Now;
             DateTime dt2;
             Int32 Fen =0;
             if (context.Session["RSubmitTime"] != null)
             {
                 dt2 = (DateTime)context.Session["RSubmitTime"];
                 Fen = (Int32)(((dt1.Ticks - dt2.Ticks) / 600000000));
                 context.Session["RSubmitTime"] = null;
             }
             

             if (cdid > 0)
             {
                 try
                 {

                     ExamOlineDA db = new ExamOlineDA();
                     //调用题目
                       //topall
                     if (topAll.Length > 0)
                     {
                         List<sheet_reply> mbItem = JsonConvert.DeserializeObject<List<sheet_reply>>(topAll);

                        
                         db.PostAllTopicReply(cdid, mbItem);
                         
                     }
                     //
                     ReadOver ro = new ReadOver(cdid);
                     ro.ReadTopic();


                     




                     if (db.UpdateTime(cdid, Fen) > 0)
                     {
                         msg.IsSuccess = 1;
                     }
                     else
                     {
                         msg.IsSuccess = 0;
                         msg.Msg = "提交失败";
                     }
                 }
                 catch (Exception er)
                 {
                     msg.IsSuccess = 0;
                     msg.Msg = er.Message;
                 }
             }

          

            context.Response.Write(JsonConvert.SerializeObject(msg));
        }

       
        /// <summary>
        /// 初始化考场
        /// </summary>
        void InitExam()
        {
            var context = System.Web.HttpContext.Current;
           
             //session计时
            if( context.Session["RSubmitTime"] ==null)
                context.Session["RSubmitTime"] = DateTime.Now;

            int examid = context.Request.Params["examid"].ToInt();
            msg.IsSuccess = 0;
            loginInfo lu = chklogin();
            if (lu != null)
            {
                if (examid > 0)
                {
                    try
                    {
                        ExamOlineDA db = new ExamOlineDA();
                        msg.IsSuccess = db.Initcandidate(lu.M_ID, examid);

                        //获得考试ID
                        msg.Data = new { id = msg.IsSuccess };
                    }
                    catch (Exception er)
                    {
                        msg.IsSuccess = 0;
                        msg.Msg = er.Message;
                    }
                }
                else {
                    msg.Msg = "请传入考场编号";
                }
            }


            context.Response.Write(JsonConvert.SerializeObject(msg));
        }
        //获得试题信息
        void GetExamView()
        {
            var context = System.Web.HttpContext.Current;
            loginInfo lu = chklogin();

            if (lu != null)
            {
                int examid = context.Request.Params["examid"].ToInt();
                int cdid = context.Request.Params["kaoshiId"].ToInt();
                try
                {
                    ViewSubject db = new ViewSubject(cdid,examid);
                    ExamDataManageEx list = db.Generate();
                   
                    msg.IsSuccess = 1;
                    msg.Data = list;
                }
                catch (Exception er)
                {
                    msg.IsSuccess = -1;
                    msg.Msg = er.Message;
                    msg.Data = null;
                }

            }
            else
            {
                msg.IsSuccess = -9;
                msg.Msg = "登陆失效，请重新登陆!";
                msg.Data = null;
            }
            context.Response.Write(JsonConvert.SerializeObject(msg));
        }
        //获得试题信息
        void GetExam()
        {
              var context = System.Web.HttpContext.Current;
             loginInfo lu = chklogin();
           
             if (lu != null)
             {
                 int examid = context.Request.Params["examid"].ToInt();
                 int cdid = context.Request.Params["kaoshiId"].ToInt();
                 try
                 {
                     GenerateTopic db = new GenerateTopic(examid, cdid);
                     ExamDataManage list = db.Generate();
                     list.comminfo.userid = lu.M_ID;
                     list.comminfo.username = lu.M_NAME;
                     msg.IsSuccess = 1;
                     msg.Data = list;
                 }
                 catch (Exception er) {
                     msg.IsSuccess = -1;
                     msg.Msg = er.Message;
                     msg.Data = null;
                 }
                
             }
             else
             {
                 msg.IsSuccess = -9;
                 msg.Msg = "登陆失效，请重新登陆!";
                 msg.Data = null;
             }
            context.Response.Write(JsonConvert.SerializeObject(msg));
        }

        /// <summary>
        /// 获得考场
        /// </summary>
        void GetexaminationList()
        { 
              var context = System.Web.HttpContext.Current;
             loginInfo lu = chklogin();
           
             if (lu != null)
             {
                 PageView pageInfo = new PageView();
                 pageInfo.PageIndex = context.Request.Params["page"].ToInt(1);
                 pageInfo.PageSize = context.Request.Params["pagesize"].ToInt(20);
                 pageInfo.SortName = context.Request.Params["sortname"].ToStr();
                 pageInfo.SortOrder = context.Request.Params["sortorder"].ToStr();
                 pageInfo.SearchParams = context.Request.Params;
                 string url = "";

                 PageList<object> List = new examinationDA().getexaminationList(lu.J_ID,lu.M_ID,pageInfo);


                 string Rjson = @"{""Rows"":null,""Total"":""0"",""Url"":""""}";
                 if (List.Data != null)
                 {
                     Rjson = @"{""Rows"":" + List.Data.ToJson() + @",""Total"":""" + List.Total + @""",""Url"":""" + url + @"""}";
                 }


                 context.Response.Write(Rjson);
             }
             else
             {
                 string Rjson = @"{""Rows"":null,""Total"":""0"",""Url"":""""}";

                 context.Response.Write(Rjson);
             }
           
        }
        loginInfo chklogin()
        {
            try
            {
                return SessionShard.loginUser;
            }
            catch
            {
                msg.IsSuccess = -9;
                msg.Msg = "登陆失效，请重新登陆!";
                return null;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}